<?php

namespace bxkj_common;

use bxkj_common\service\Sevrice;
use Qiniu\Auth;
use think\Exception;

class Qiniu
{
    public function upload($params)
    {
        try {
            $filename = $params['filename'];
            $userId = isset($params['user_id']) ? $params['user_id'] : 0;
            $type = $params['type'];
            $userKey = isset($params['user_key']) ? $params['user_key'] : 'user_id';

            if (empty($type)) return ['code' => 101, 'msg' => lang('UPLOAD_TYPE_CANTNOT_EMPTY')];
            if (empty($filename)) return ['code' => 102, 'msg' => lang('UPLOAD_FILE_CANTNOT_EMPTY')];

            $config = config('upload');
            $platform_config = $config['platform_config'];

            $accessKey = $platform_config['access_key'];
            $secretKey = $platform_config['secret_key'];
            $bucket = $platform_config['bucket'];
            $auth = new Auth($accessKey, $secretKey);
            $uploadConfig = $config['upload_config'];
            if (empty($uploadConfig[$type])) return ['code' => 103, 'msg' => lang('UPLOAD_TYPE_NOT_EXIST')];
            $config = array_merge(($uploadConfig['_default'] ? $uploadConfig['_default'] : array()), $uploadConfig[$type]);

            $policy = array(
                'callbackUrl' => "",
                'callbackBody' => '{"key": "$(key)","hash": "$(etag)","fsize": "$(fsize)","bucket": "$(bucket)","name": "$(x:name)","w": "$(imageInfo.width)","h":"$(imageInfo.height)","fname": "$(fname)","mimeType": "$(mimeType)","uuid": "$(uuid)"}',
                'callbackBodyType' => 'application/json',
            );
            $expires = 3600;
            if (isset($config['fsizeMin'])) $policy['fsizeMin'] = (int)$config['fsizeMin'];
            if (isset($config['fsizeLimit'])) $policy['fsizeLimit'] = (int)$config['fsizeLimit'];
            if (isset($config['mimeLimit'])) $policy['mimeLimit'] = $config['mimeLimit'];

            $key = make_qiniu_key($filename, $config, $userId, $userKey);
            $upToken = $auth->uploadToken($bucket, $key, $expires, $policy, true);
            if (!$upToken) return ['code' => 104, 'msg' => 'make token error'];
            if (strpos($platform_config['base_url'], ',')) {
                @list($base_url, ) = explode(',', $platform_config['base_url']);
            } else{
                $base_url = $platform_config['base_url'];
            }

            $base = $base_url;
            $result['token'] = $upToken;
            $result['key'] = $key;
            $result['expires'] = $expires;
            $result['base'] = $base;
            $result['fsizeMin'] = $policy['fsizeMin'];
            $result['fsizeLimit'] = $policy['fsizeLimit'];
            $result['mimeLimit'] = $policy['mimeLimit'];
            $result['url'] = $base . '/' . ltrim($key, '/');

        } catch (Exception $e) {
            return ['code' => 500, 'msg' => $e->getMessage()];
        }

        return ['code' => 200, 'result' => $result];
    }
}